
/* ******************************************************************
 * This file is part of the escal project and distributed under the
 * terms of the GNU General Public License Version 3
 * CopyRight (C) 2008 Epocher (xijiaosdq@gmail.com)
 * See COPYING file for licensing information.
 *******************************************************************/

#include "ftp_link_manager.h"

FtpLinkManager::FtpLinkManager(FileManager *fileManager, const QUrl &url,
		QObject *parent)
	:BaseLinkManager(parent)
{
	this->url = url;
	this->fileManager = fileManager;
	this->pieceIndex = 0;
	this->offset = 0;
	reconnect = false;
	gotPiece = false;
	error = false;
	quit = false;
	connect(&ftp, SIGNAL(readyRead()), 
		this, SLOT(readData()));
	connect(&ftp, SIGNAL(done( bool)),
		this, SLOT(ftpRequestDone( bool)));
	connect(&ftp, SIGNAL(dataTransferProgress(qint64, qint64)),
		this, SLOT(updateDataReadProgress(qint64, qint64)));
};

FtpLinkManager::~FtpLinkManager(){
	stop();
	cleanUp();
};

void FtpLinkManager::cleanUp(){
    if(gotPiece){
        fileManager->releasePiece(pieceIndex);
	gotPiece=false;
    }
};

void FtpLinkManager::stop(){
	quit = true;
	ftp.abort();
	QThread::quit();
	wait();
};

void FtpLinkManager::run(){
	startDownload();
	exec();
};

void FtpLinkManager::startDownload(){
	reconnect = false;
	error = false;
	quit = false;
	if(!fileManager->isNew()){
        	if(!gotPiece && ((pieceIndex = fileManager->getPiece()) <0)){
	    		error = true;
	    		emit linkQuited(this, true);
			exit(0);
			return;
		}
		else{
			gotPiece = true;
		}
	}
	ftp.connectToHost(url.host(), url.port(21));
	ftp.login(QUrl::fromPercentEncoding(url.userName().toLatin1()),
			url.password());
	QString dirPath = url.path();
	dirPath.resize(dirPath.lastIndexOf("/"));
	QString filePath = url.path();
	filePath.remove(0, filePath.lastIndexOf("/")+1);
	qDebug() << dirPath << filePath;
	ftp.cd(dirPath);
	ftp.get(filePath);
}

void FtpLinkManager::readData( ){
	qDebug() << "FtpLinkManager::readData( )";
	QByteArray data = ftp.readAll();
	qDebug() << pieceIndex << offset;

	if((reconnect = fileManager->write(pieceIndex, offset, data))){
		qDebug() << "reconnect = fileManager->write(pieceIndex, offset, data)))";
		offset = 0;
		pieceIndex = fileManager->getPiece();
		if(pieceIndex <=0){
			qDebug() << "pieceIndex <0";
			reconnect = false;
			gotPiece = false;
		}
		ftp.abort();
	}
}

void FtpLinkManager::ftpRequestDone(bool error){
	qDebug() << "ftpLinkManager::httpRequestDone()";
	if(error) qDebug() << ftp.errorString();
	if(quit || !reconnect || this->error){
		QThread::exit(0);
		//emit linkQuit();
		emit linkQuited(this, this->error);
	}
	else{
		reconnect = false;
		startDownload();
	}
}

void FtpLinkManager::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes){	
	qDebug() << bytesRead << totalBytes;
	if(totalBytes < 0){
		qDebug() << "totalBytes < 0";
		error = 1;
		ftp.abort();
	}
	else if(fileManager->isNew()){
		fileManager->initNewFile(totalBytes, false);
		pieceIndex = fileManager->getPiece();
		if(pieceIndex >=0) gotPiece = true;
		else {
			qDebug() << "pieceIndex >=0";
			error = true;
			ftp.abort();
		}
	}
}

